import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {UserService} from '../../user/service/user.service';
import {Blog} from '../model/blog';
import {Catalog} from '../model/catalog';
import {Message} from 'primeng/components/common/api';

@Component({
  selector: 'app-writeoreditpost',
  templateUrl: './writeoreditpost.component.html',
  styleUrls: ['./writeoreditpost.component.css']
})
export class WriteoreditpostComponent implements OnInit {

  blog: Blog = new Blog();
  catalogs: Catalog[];
  msgs: Message[] = [];

  constructor(public http: HttpClient, public router: Router,
              public route: ActivatedRoute, public userService: UserService) {
  }

  ngOnInit() {
    this.http.get('/catalogs').subscribe(result => {
      if (result['error']) {
        this.router.navigateByUrl('/user/login');
      } else {
        this.catalogs = result['data'];
      }
    });
    this.route.params.subscribe((params: Params) => {
      if (params['id']) {
        this.http.get('blog?id=' + params['id']).subscribe(result => {
          if (result['error']) {
            this.router.navigateByUrl('/posts');
          } else {
            this.blog = result['data'];
          }
        });
      }
    });
  }

  onSubmit() {
    if (this.blog.catalog.id == null) {
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '必须选择分类'});
      return;
    }
    if (this.blog.title == null || this.blog.title == '' || this.blog.summary == null || this.blog.summary == '' || this.blog.htmlContent == null || this.blog.htmlContent == '') {
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '标题,摘要,正文任何一个都不能为空'});
      return;
    }

    this.http.post('/blog', this.blog).subscribe(result => {
      if (result['error'] == '未登录') {
        this.router.navigateByUrl("/user/login");
        this.userService.currentUser=null;
      }
      if(result['error']==''){
        this.blog = result['data'];
        this.router.navigateByUrl('/post/'+this.blog.id);
      }
      if(result['error']){
        this.msgs = [];
        this.msgs.push({severity: 'error', summary: result['error']});
      }
    });

  }

}
